<template>
  <div class="app-container">
    <el-row type="flex" class="row-bg btn-row" justify="end">
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('1024')" @click="showModal(null, 'Batch Assign')" type="primary">{{$t('orderWithdraw.batch_assign')}}</el-button>
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('1025')" @click="exportData" type="primary" icon="el-icon-plus">{{$t('orderWithdraw.download')}}</el-button>
    </el-row>
    <el-collapse>
      <el-collapse-item>
        <div slot="title">
          &nbsp;&nbsp;&nbsp;{{$t('orderWithdraw.click_filter')}}&nbsp;&nbsp;&nbsp;<i class="icon iconfont icon-filter" style="font-size: 10px"></i>
        </div>
        <el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left" >
          <el-form-item :label="$t('orderWithdraw.id')">
            <el-input v-model="q.id" :placeholder="$t('orderWithdraw.id')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.mch_id')">
            <el-select v-model="q.mch_id" :placeholder="$t('orderWithdraw.select')">
              <el-option :label="$t('orderWithdraw.all')" :value=null></el-option>
              <el-option v-for="mch of MchList" :key="mch.id" :label="mch.name" :value="mch.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.mch_order_no')">
            <el-input v-model="q.mch_order_no" :placeholder="$t('orderWithdraw.mch_order_no')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.player_id')" filterable>
            <el-input v-model="q.player_id" :placeholder="$t('orderWithdraw.player_id')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.status')">
            <el-select v-model.number="q.status" :placeholder="$t('orderWithdraw.select')">
              <el-option :label="$t('orderWithdraw.all')" :value=null></el-option>
              <el-option v-for="(status, index) of OrderStatusArray" :key="index" :label="status" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.notify_status')">
            <el-select v-model.number="q.notify_status" :placeholder="$t('orderWithdraw.select')">
              <el-option :label="$t('orderWithdraw.all')" :value=null></el-option>
              <el-option v-for="(statu, index) of NotifyStatusArray" :key="index" :label="statu" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.card_name')">
            <el-input v-model="q.bankcard_name" :placeholder="$t('order.receiving_card_name')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('orderWithdraw.amount')">
            <el-input v-model="q.amount" :placeholder="$t('orderWithdraw.amount')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <!-- <el-form-item :label="$t('orderWithdraw.exact_amount')">
            <el-input v-model="q.exact_amount" :placeholder="$t('orderWithdraw.exact_amount')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="text" disabled>{{this.Timetype?$t('orderWithdraw.created_at'):$t('orderWithdraw.exact_time')}}</el-button>
            (<el-button type="text" @click="toggleTimetype">{{$t('orderWithdraw.click_switch')}}</el-button>)
            <el-date-picker v-if="Timetype" v-model="created_at.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('orderWithdraw.select_datetime')"></el-date-picker>
            <el-date-picker v-else v-model="exact_time.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('orderWithdraw.select_datetime')"></el-date-picker>
            -
            <el-date-picker v-if="Timetype" v-model="created_at.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('orderWithdraw.select_datetime')"></el-date-picker>
            <el-date-picker v-else v-model="exact_time.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('orderWithdraw.select_datetime')"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="query">{{$t('orderWithdraw.search')}}</el-button>
            <el-button type="danger" @click="reload">{{$t('orderWithdraw.reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <el-row>
      <el-col >
        {{$t('orderWithdraw.total_success_order')}}: <span style="color: #f00;line-height: 80px">{{listData.amount ? listData.amount.toFixed(2) : "0.00"}}</span>{{$t('order.rmb')}}&nbsp;&nbsp;&nbsp;&nbsp;
        {{$t('orderWithdraw.total_exact_amount')}}: <span style="color: #f00;line-height: 80px">{{listData.exact_amount ? listData.exact_amount.toFixed(2) : "0.00"}}</span>{{$t('order.rmb')}}
      </el-col>
    </el-row>
    <el-table :data="listData.list" v-loading.body="listLoading" @sort-change="sortlist" element-loading-text="Loading" stripe border fit highlight-current-row
              @select-all="handleSelectionChange">
      <el-table-column label='Selected' width="40" type="selection">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.selected" ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="id" :label="$t('orderWithdraw.id')" sortable width="170"></el-table-column>
      <el-table-column prop="mch_id" :label="$t('orderWithdraw.mch_id')" sortable width="100"></el-table-column>
      <el-table-column prop="source_card_code" :label="$t('orderWithdraw.first_card')" sortable width="120"></el-table-column>
      <el-table-column prop="destination_card_code" :label="$t('orderWithdraw.second_card')" sortable width="120"></el-table-column>
      <el-table-column prop="amount" :label="$t('orderWithdraw.amount')" sortable width="120"></el-table-column>
      <el-table-column prop="exact_amount" :label="$t('orderWithdraw.exact_amount')" sortable width="120"></el-table-column>
      <el-table-column prop="status" :label="$t('orderWithdraw.status')" width="100">
        <template slot-scope="scope">{{OrderStatusArray[scope.row.status]}}</template>
      </el-table-column>
      <el-table-column prop="created_at" :label="$t('orderWithdraw.created_at')" sortable width="155"></el-table-column>
      <el-table-column prop="operating_time" :label="$t('orderWithdraw.operating_time')" sortable width="155"></el-table-column>
      <el-table-column prop="exact_time" :label="$t('orderWithdraw.exact_time')" sortable width="155"></el-table-column>
      <el-table-column :label="$t('orderWithdraw.action')" width="140" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="showModal(scope.row, 'View')" v-if="$store.state.user.user_perms.includes('1022')">{{$t('orderWithdraw.view')}}</el-button>
          <el-button type="text" @click="showModal(scope.row, 'Edit')" v-if="$store.state.user.user_perms.includes('1023') && !orderFinished.includes(scope.row.status)">{{$t('orderWithdraw.edit')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="q.$page" :page-sizes="$store.state.app.pageSizeArr"
                      :page-size="q.$size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="listData.total_count">
      </el-pagination>
    </div>

    <order-modal :modalOrderData="modalOrderData" @ok="modalOk"></order-modal>
    <order-batch-modal :modalOrderData="modalOrderData" @ok="modalOk"></order-batch-modal>

  </div>
</template>

<script>
  import { json2excel } from 'js2excel';
  import { getOrderWithdrawList, getMchList } from '@/api/merchant'
  import { queryFilter } from '@/utils/patch'
  import { jsonKeyToTitleCase } from '@/utils/index'
  import orderModal from './orderModal'
  import orderBatchModal from './orderBatchModal'
  export default {
    components: { orderModal, orderBatchModal },
    data() {
      return {
        listData: {},
        created_at: {},
        exact_time: {},
        MchList: [],
        Timetype: true,
        q: {$size: 30, $page: 1, order_type: '5'},
        listLoading: true,
        modalOrderData: {
          selectedOrder: {},
          title: 'View Order',
          action: 'View',
          show: false,
          cancelTitle: 'Cancel',
          batch: false,
          batchOrder: [],
          batchHeader: '',
          batchIcon: ''
        },
        multipleSelect: false,
        orderFinished: [2,3,4] /* 2 - Success, 3 - Manual Success, 4 - Invalid */
      }
    },
    created() {
      this.getList()
      this.getMchList()
    },
    deactivated(){
      this.listLoading = false
    },
    computed: {
      OrderStatusArray: function() {
        return [this.$t('orderWithdraw.pending'),
          this.$t('orderWithdraw.processing'),
          this.$t('orderWithdraw.success'),
          this.$t('orderWithdraw.manual_success'),
          this.$t('orderWithdraw.invalid'),
          this.$t('orderWithdraw.paying')]
      },
      NotifyStatusArray: function() {
        return [this.$t('orderWithdraw.notify_none'),
          this.$t('orderWithdraw.notify_failed'),
          this.$t('orderWithdraw.notify_success')]
      }
    },
    methods: {
      query(){
        this.getList()
      },
      reload() {
        this.created_at = this.exact_time = {}
        this.q = {$size: this.q.$size, $page: this.q.$page, order_type: '5'}
        this.getList()
      },
      sortlist(sort){
        this.q.$orderby = sort.prop
        this.getList()
      },
      handleSizeChange (val) {
        this.q.$size = val
        this.getList()
      },
      handleCurrentChange (val) {
        this.q.$page = val
        this.getList()
      },
      showModal(order, action) {
        let selectedOrders;
        this.modalOrderData.batch = false;
        this.modalOrderData.batchOrder = [];
        switch (action) {
          case 'View':
            this.modalOrderData.selectedOrder = {...order};
            this.modalOrderData.title = `${action} Order`;
            this.modalOrderData.action = action;
            this.modalOrderData.show = true;
            this.modalOrderData.cancelTitle = 'Close';
            break;
          case 'Edit':
            const selectedOrder = {...order}
            selectedOrder.status = ''
            this.modalOrderData.selectedOrder = selectedOrder;
            this.modalOrderData.title = `${action} Order`;
            this.modalOrderData.action = action;
            this.modalOrderData.show = true;
            this.modalOrderData.cancelTitle = 'Cancel';
            this.modalOrderData.okTitle = 'Update'
            break;
          case 'Batch Assign':
            selectedOrders = this.listData.list.filter(order => order.selected);
            if(selectedOrders.length <= 0) {
              this.$message({type: 'warning', message: this.$t('orderWithdraw.batch_select') + this.$t('orderWithdraw.' + action.toLowerCase().replace(' ', '_'))})
              return;
            }

            this.modalOrderData.title = `${action} Order`;
            this.modalOrderData.action = action;
            this.modalOrderData.show = true;
            this.modalOrderData.cancelTitle = 'Cancel';
            this.modalOrderData.batch = true;
            this.modalOrderData.batchOrder = selectedOrders;
            this.modalOrderData.batchHeader = 'Do you want to continue edit the status to the following Orders?';
            this.modalOrderData.batchIcon = 'cui-arrow-right';
            this.modalOrderData.okTitle = action
            break;
        }
      },
      modalOk(evt) {
        switch (this.modalOrderData.action) {
          case 'View':
            break;
          case 'Edit':
          case 'Batch Assign':
        }
      },
      toggleTimetype() {
        if (!this.Timetype) {
          this.created_at = {}
          delete this.q.created_at
          this.Timetype = !this.Timetype
        } else {
          this.exact_time = {}
          delete this.q.exact_time
          this.Timetype = !this.Timetype
        }
      },
      handleTime() {
        if (this.created_at.$gte || this.created_at.$lt) {
          this.q.created_at = {}
          if(this.created_at.$gte) {
            this.q.created_at.$gte = this.created_at.$gte
          }
          if(this.created_at.$lt) {
            this.q.created_at.$lt = this.created_at.$lt
          }
        }
        if (this.exact_time.$gte || this.exact_time.$lt) {
          this.q.exact_time = {}
          if(this.exact_time.$gte) {
            this.q.exact_time.$gte = this.exact_time.$gte
          }
          if(this.exact_time.$lt) {
            this.q.exact_time.$lt = this.exact_time.$lt
          }
        }
      },
      exportData() {
        this.getList(true)
      },
      getList(isDownload = false) {
        this.handleTime()
        let params = Object.assign({
          $orderby: '-id'
        }, this.q)

        if(params.id && isNaN(params.id)) {
          this.$message({type: 'info',message: 'Please enter a number in the search ID'})
          return;
        }

        if(isDownload){
          params['$size'] = 9999999999
        }

        let queryObj = queryFilter(params)
        this.listLoading = true

        getOrderWithdrawList(queryObj).then(res => {
          if (res.status === 0) {
            if(isDownload){
              this.listLoading = false
              let orders = [...res.data.list]
              let downloadData = orders.map(order => ({
                id: order.id,
                mch_id: order.mch_id,
                source_card_code: order.source_card_code,
                destination_card_code: order.destination_card_code,
                source_account_name: order.source_account_name,
                source_account_number: order.source_account_number,
                source_bank: order.source_bank,
                account_name: order.account_name,
                account_number: order.account_number,
                bank: order.bank,
                amount: order.amount,
                status: this.OrderStatusArray[order.status],
                notes: order.notes,
                created_at: order.created_at,
                operating_time: order.operating_time,
                exact_time: order.exact_time,
                updated_at: order.updated_at
              }));
              var exportData = jsonKeyToTitleCase(downloadData)
              json2excel({ data: exportData, name: 'BufferWithdrawOrderList', formateDate: 'yyyy/mm/dd' })
            } else {
              this.listLoading = false
              this.listData = res.data
            }
          }
        })
      },
      getMchList(){
        getMchList({$size: -1}).then(res => {
          if (res.status === 0) {
            this.MchList = res.data.list
          }
        })
      },
      handleSelectionChange(val) {
        this.multipleSelect = !this.multipleSelect;
        this.listData.list.forEach(element => {
          element.selected = this.multipleSelect;
        });
      }
    }
  }

  export const enOrderWithdraw = {
    // General
    loading: 'loading',
    total_success_order: 'Total Application Amount',
    total_exact_amount: 'Total Exact Amount',
    click_filter: 'Click to filter',
    all: 'All',
    confirm: 'OK',
    cancel: 'Cancel',
    cancelled: 'Cancelled',
    rmb: 'RMB',

    // Search and Filters
    select: 'Please choose',
    click_switch: 'Click to switch',
    select_datetime: 'Selecte date and time',

    // Table
    id: 'Hydra ID',
    mch_id: 'Company',
    mch_order_no: 'UA Order No',
    player_id: 'Player ID',
    source_card_code: 'Card Code',
    amount: 'Application Amount',
    exact_amount: 'Exact Amount',
    status: 'Status',
    notify_status: 'Notify Status',
    notify_count: 'Notify Count',
    created_at: 'Application Time',
    operating_time: 'Operating Time',
    exact_time: 'Exact Time',
    updated_at: 'Updated At',
    action: 'Action',

    // Action Link and Buttons
    batch_assign: 'Batch Assign',
    batch_push: 'Batch Push',
    download: 'Download',
    view: 'View',
    edit: 'Edit',
    push: 'Push',
    search: 'Search',
    reset: 'Reset',

    // Order Status
    pending: 'Pending',
    processing: 'Processing',
    success: 'Success',
    manual_success: 'Manual Success',
    invalid: 'Invalid',
    paying: 'Paying',

    // Notify Status
    notify_none: 'None',
    notify_success: 'Success',
    notify_failed: 'Failed',

    // Messages
    push_confirm: 'Do you want to continue push',
    push_successful: 'Successfuly pushed!',
    batch_select: 'Please select orders to '
  }

  export const zhOrderWithdraw = {
    // General
    loading: 'loading',
    total_success_order: '成功下单金额总计',
    total_exact_amount: '真实到账金额总计',
    click_filter: '点击筛选',
    all: '所有',
    confirm: '确定',
    cancel: '取消',
    cancelled: '取消',
    rmb: '元',

    // Search and Filters
    select: '请选择',
    click_switch: '点击切换',
    select_datetime: '选择日期时间',

    // Table
    id: 'Hydra ID',
    mch_id: '公司',
    mch_order_no: 'UA订单号',
    player_id: '玩家账号',
    source_card_code: '銀行卡編號',
    amount: '申请金额',
    exact_amount: '实际金额',
    status: '订单状态',
    notify_status: '回调状态',
    notify_count: '回调次数',
    created_at: '申请时间',
    operating_time: '处理时间',
    exact_time: '完成时间',
    updated_at: '更新时间',
    action: '操作',

    // Action Link and Buttons
    batch_assign: '批量分配',
    batch_push: '批量推送',
    download: '导出订单',
    view: '查看',
    edit: '編輯',
    push: '推送',
    search: '查询',
    reset: '重置',

    // Order Status
    pending: '有待',
    processing: '处理',
    success: '成功',
    manual_success: '手动成功',
    invalid: '无效',
    paying: '支付中',

    // Notify Status
    notify_none: '未回调',
    notify_success: '回调成功',
    notify_failed: '回调失败',

    // Messages
    push_confirm: '你想继续推吗',
    push_successful: '成功推送!',
    batch_select: '请选择订单'

  }
</script>

<style lang="scss" scoped>
  .flex-display {
    display: flex;
    justify-content: center
  }

</style>
